{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<a href=\"https://colab.research.google.com/github/run-llama/llama_index/blob/main/docs/examples/llm/cerebras.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Cerebras\n",
    "\n",
    "At Cerebras, we've developed the world's largest and fastest AI processor, the Wafer-Scale Engine-3 (WSE-3). The Cerebras CS-3 system, powered by the WSE-3, represents a new class of AI supercomputer that sets the standard for generative AI training and inference with unparalleled performance and scalability.\n",
    "\n",
    "With Cerebras as your inference provider, you can:\n",
    "- Achieve unprecedented speed for AI inference workloads\n",
    "- Build commercially with high throughput\n",
    "- Effortlessly scale your AI workloads with our seamless clustering technology\n",
    "\n",
    "Our CS-3 systems can be quickly and easily clustered to create the largest AI supercomputers in the world, making it simple to place and run the largest models. Leading corporations, research institutions, and governments are already using Cerebras solutions to develop proprietary models and train popular open-source models.\n",
    "\n",
    "Want to experience the power of Cerebras? Check out our [website](https://cerebras.net) for more resources and explore options for accessing our technology through the Cerebras Cloud or on-premise deployments!\n",
    "\n",
    "For more information about Cerebras Cloud, visit [cloud.cerebras.ai](https://cloud.cerebras.ai/). Our API reference is available at [inference-docs.cerebras.ai](https://inference-docs.cerebras.ai/)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you're opening this Notebook on colab, you will probably need to install LlamaIndex 🦙."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "% pip install llama-index-llms-cerebras"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!pip install llama-index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.llms.cerebras import Cerebras"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Get an API Key from [cloud.cerebras.ai](https://cloud.cerebras.ai/) and add it to your environment variables:\n",
    "\n",
    "\n",
    "```bash\n",
    "export CEREBRAS_API_KEY=<your api key>\n",
    "```\n",
    "\n",
    "Alternatively, you can pass your API key to the LLM when you init it:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Enter your Cerebras API key:  ········\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import getpass\n",
    "\n",
    "os.environ[\"CEREBRAS_API_KEY\"] = getpass.getpass(\n",
    "    \"Enter your Cerebras API key: \"\n",
    ")\n",
    "\n",
    "llm = Cerebras(model=\"llama-3.3-70b\", api_key=os.environ[\"CEREBRAS_API_KEY\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "A list of available LLM models can be found at [inference-docs.cerebras.ai](https://inference-docs.cerebras.ai/)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "response = llm.complete(\"What is Generative AI?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Generative AI refers to a type of artificial intelligence (AI) that is capable of generating new, original content, such as text, images, music, or videos, based on patterns and structures it has learned from a dataset or a set of examples. This type of AI is designed to create new content that is similar in style, tone, and quality to the original content it was trained on.\n",
      "\n",
      "Generative AI models use various techniques, such as neural networks, to analyze and learn from large datasets, and then generate new content that is similar to the patterns and structures they have learned. These models can be trained on a wide range of data, including text, images, audio, and video, and can be used to generate a variety of content, such as:\n",
      "\n",
      "1. Text: Generative AI models can generate text that is similar in style and tone to a given text, such as articles, blog posts, or social media updates.\n",
      "2. Images: Generative AI models can generate images that are similar in style and content to a given image, such as photographs, illustrations, or graphics.\n",
      "3. Music: Generative AI models can generate music that is similar in style and tone to a given piece of music, such as melodies, harmonies, or beats.\n",
      "4. Videos: Generative AI models can generate videos that are similar in style and content to a given video, such as animations, movies, or TV shows.\n",
      "\n",
      "Generative AI has many potential applications, including:\n",
      "\n",
      "1. Content creation: Generative AI can be used to generate content for various industries, such as marketing, advertising, and entertainment.\n",
      "2. Data augmentation: Generative AI can be used to generate new data that can be used to train and improve machine learning models.\n",
      "3. Creative collaboration: Generative AI can be used to collaborate with humans in the creative process, such as generating ideas or providing inspiration.\n",
      "4. Personalization: Generative AI can be used to generate personalized content for individuals, such as customized recommendations or tailored marketing messages.\n",
      "\n",
      "Some examples of generative AI include:\n",
      "\n",
      "1. Language models like GPT-3, which can generate human-like text based on a prompt.\n",
      "2. Image generation models like Generative Adversarial Networks (GANs), which can generate realistic images of faces, objects, or scenes.\n",
      "3. Music generation models like Amper Music, which can generate original music tracks based on a set of parameters.\n",
      "4. Video generation models like DeepMotion, which can generate realistic videos of human movements and actions.\n",
      "\n",
      "Overall, generative AI has the potential to revolutionize the way we create and interact with content, and has many exciting applications across various industries.\n"
     ]
    }
   ],
   "source": [
    "print(response)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Call `chat` with a list of messages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.llms import ChatMessage\n",
    "\n",
    "messages = [\n",
    "    ChatMessage(\n",
    "        role=\"system\", content=\"You are a pirate with a colorful personality\"\n",
    "    ),\n",
    "    ChatMessage(role=\"user\", content=\"What is your name\"),\n",
    "]\n",
    "resp = llm.chat(messages)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "assistant: Arrrr, me hearty! Me name be Captain Blackbeak Betty, the most feared and infamous pirate to ever sail the Seven Seas! Me and me trusty parrot, Polly, have been plunderin' and pillagin' for nigh on 20 years, and me reputation be known from the Caribbean to the coast of Africa!\n",
      "\n",
      "Now, I be a bit of a legend in me own right, with me black beard and me eye patch, and me ship, the \"Maverick's Revenge\", be the fastest and most feared on the high seas! So, if ye be lookin' for a swashbucklin' adventure, just give ol' Blackbeak Betty a shout, and we'll set sail fer a life o' plunder and pillage! Savvy?\n"
     ]
    }
   ],
   "source": [
    "print(resp)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Streaming"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Using `stream_complete` endpoint "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "response = llm.stream_complete(\"What is Generative AI?\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Generative AI refers to a type of artificial intelligence (AI) that is capable of generating new, original content, such as text, images, music, or videos, based on patterns and structures it has learned from a dataset or a set of examples. This type of AI is designed to create new content that is similar in style, tone, and quality to the original content it was trained on.\n",
      "\n",
      "Generative AI models use various techniques, such as neural networks, to analyze and learn from large datasets, and then generate new content that is similar to the patterns and structures they have learned. These models can be trained on a wide range of data, including text, images, audio, and video, and can be used to generate a variety of content, such as:\n",
      "\n",
      "1. Text: Generative AI models can generate text that is similar in style and tone to a given text, such as articles, blog posts, or social media updates.\n",
      "2. Images: Generative AI models can generate images that are similar in style and content to a given image, such as photographs, illustrations, or graphics.\n",
      "3. Music: Generative AI models can generate music that is similar in style and tone to a given piece of music, such as melodies, harmonies, or beats.\n",
      "4. Videos: Generative AI models can generate videos that are similar in style and content to a given video, such as animations, movies, or TV shows.\n",
      "\n",
      "Generative AI has many potential applications, including:\n",
      "\n",
      "1. Content creation: Generative AI can be used to generate content for various industries, such as marketing, advertising, and entertainment.\n",
      "2. Data augmentation: Generative AI can be used to generate new data that can be used to train and improve machine learning models.\n",
      "3. Creative collaboration: Generative AI can be used to collaborate with humans in the creative process, such as generating ideas or providing inspiration.\n",
      "4. Personalization: Generative AI can be used to generate personalized content for individuals, such as customized recommendations or tailored marketing messages.\n",
      "\n",
      "Some examples of generative AI include:\n",
      "\n",
      "1. Language models like GPT-3, which can generate human-like text based on a prompt.\n",
      "2. Image generation models like Generative Adversarial Networks (GANs), which can generate realistic images of faces, objects, or scenes.\n",
      "3. Music generation models like Amper Music, which can generate original music tracks based on a set of parameters.\n",
      "4. Video generation models like DeepMotion, which can generate realistic videos of human movements and actions.\n",
      "\n",
      "Overall, generative AI has the potential to revolutionize the way we create and interact with content, and has many exciting applications across various industries."
     ]
    }
   ],
   "source": [
    "for r in response:\n",
    "    print(r.delta, end=\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Using `stream_chat` endpoint"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core.llms import ChatMessage\n",
    "\n",
    "messages = [\n",
    "    ChatMessage(\n",
    "        role=\"system\", content=\"You are a pirate with a colorful personality\"\n",
    "    ),\n",
    "    ChatMessage(role=\"user\", content=\"What is your name\"),\n",
    "]\n",
    "resp = llm.stream_chat(messages)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Arrrr, me hearty! Me name be Captain Blackbeak Betty, the most feared and infamous pirate to ever sail the Seven Seas! Me and me trusty parrot, Polly, have been plunderin' and pillagin' for nigh on 20 years, and me reputation be known from the Caribbean to the coast of Africa!\n",
      "\n",
      "Now, I be a bit of a legend in me own right, with me black beard and me eye patch, and me ship, the \"Maverick's Revenge\", be the fastest and most feared on the high seas! So, if ye be lookin' for a swashbucklin' adventure, just give ol' Blackbeak Betty a shout, and we'll set sail fer a life o' plunder and pillage! Savvy?"
     ]
    }
   ],
   "source": [
    "for r in resp:\n",
    "    print(r.delta, end=\"\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
